<?php

namespace App\Models;

use Image;

class ShopGoods extends BaseModel
{
    protected $table = "shop_goods";

    protected $redisListTable = "shop_goods_list";

    protected $redisKeyTable = "shop_goods_list_keys";

    const SHOP_GOODS_DATA = 'SHOP_GOODS_DATA';

    protected $rules = [
        'admin_id' => 'required',
        'shop_id' => 'required',
        'goods_id' => 'required',
        'goods_name' => 'required|between:1,20',
        'goods_price' => ['required', 'numeric', 'regex:/^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])/'],
        'shop_price' => 'numeric',
        'goods_num' => 'required|numeric|min:1',
        'category_id' => 'required|numeric',
        'brand_id' => 'required|numeric',
        'bucket_category_id' => 'required|numeric',
    ];

    protected $message = [
        'admin_id.required' => '商户信息获取失败',
        'shop_id.required' => '店铺ID获取失败',
        'goods_id.required' => '商品ID获取失败',
        'goods_name.required' => '商品名称必须填写',
        'goods_name.between' => '商品名称不能超过20个字',
        'goods_price.required' => '商品价格必须填写',
        'goods_price.numeric' => '商品价格必须是纯数字',
        'goods_price.regex' => '商品价格不能小于0',
        'shop_price.numeric' => '市场价格必须是纯数字',
        'goods_num.required' => '商品库存必须填写',
        'goods_num.numeric' => '商品库存必须是纯数字',
        'goods_num.min' => '商品库存不能小于1',
        'category_id.required' => '请选择商品所属分类',
        'category_id.numeric' => '非法分类数据',
        'brand_id.required' => '请选择商品所属品牌',
        'brand_id.numeric' => '非法品牌数据',
        'bucket_category_id.required' => '请选择商品所属水桶分类',
        'bucket_category_id.numeric' => '非法水桶分类数据',
    ];

    public function waterBill()
    {
        return $this->hasOne('App\Models\WaterBill', 'shop_goods_id', 'id');
    }


    public function getGoodsList()
    {
        $keyword = request('keyword');
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where);
        $txtStr['status'] = [1 => '上架', -1 => '下架', 0 => '待审核'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getOwnGoodsListById($shop_id, $fields = '*')
    {
        $keyword = request('keyword');
        $where['shop_id'] = $shop_id;
//        $where['status'] = 1;
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $order['status'] = 'desc';
        $order['sort'] = 'asc';
        $rows = $this->_getPageList($where, $fields, $order);
        $txtStr['status'] = [1 => '已上架', -1 => '已下架', 0 => '待审核'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getOwnGoodsListWithBill($shopId)
    {
        $keyword = request('keyword');
        $where['admin_id'] = plat_admin_id();
        $where['shop_id'] = $shopId;
//        $where['status'] = ['>=', 0];
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        return $this->_getJoinPageList('waterBill', $where, '*', ['sort' => 'asc'], 10, 5, 'id,shop_goods_id,goods_id,waterbill_category,status', ['shop_id' => $where['shop_id'], 'status' => 1]);
    }

    public function getGoodsListByShopId($shopId)
    {
        $keyword = request('keyword');
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['goods_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        if (request('category_id')) {
            $where['category_id'] = request('category_id', 1);
        }
        $where['shop_id'] = $shopId;
        $where['status'] = ['>', 0];
        $rows = $this->_getPageList($where, 'id,goods_id,goods_name,goods_num,goods_price');
        return $rows;
    }


    public function addFromStore()
    {
        $shopId = request('shop_id');
        $ids = request('ids');
        $nums = count($ids);
        if (!(!empty($ids) && is_array($ids))) {
            $this->error = '请选择要操作的数据';
            return false;
        }
        $where['id'] = ['in', $ids];
        $where['admin_id'] = plat_admin_id();
        $goods = new Goods();
        $goodsList = $goods->_getList($where)->toArray();
        if (empty($goodsList)) {
            $this->error = '商品数据不存在';
            return false;
        }
        if (!$shopId) {
            $this->error = '非法操作';
            return false;
        }
        if (request('old')) {
            $old = explode(',', request('old'));
            $arr = array_diff($old, $ids);
            if (!empty($arr)) {
                foreach ($arr as $v) {
                    if (in_array($v, $old)) {
                        $_res = $this->checkData($arr);
                        if (!$_res) {
                            $this->error = '商品正在出售中无法删除';
                            return false;
                        }
                    }
                }
            }
            $ids = array_diff($ids, $old);
        }
        if (empty($ids)) {
            return true;
        }
        $data = [];
        foreach ($ids as $k => $v) {
            foreach ($goodsList as $n) {
                if ($n['id'] == $v) {
                    $data[] = $n;
                }
            }
        }
        if (empty($data)) {
            $this->error = '无效商品数据';
            return false;
        }
        foreach ($data as $k => $v) {
            $data[$k]['shop_id'] = $shopId;
            $data[$k]['goods_id'] = $v['id'];
            $data[$k]['addtime'] = time();
            $data[$k]['created_at'] = date('Y-m-d H:i:s');
            $data[$k]['updated_at'] = date('Y-m-d H:i:s');
            unset($data[$k]['id']);
        }
        foreach ($data as $v) {
            if (!$this->_validate($v)) {
                return false;
            }
        }
        $res = $this->_add($data);
        if (!$res) {
            $this->error = '添加失败，请稍后再试';
            return false;
        }
        $shop = new Shop();
        $shop->_update(['id' => $shopId], ['total_goods_num' => $nums]);
        $this->_redisGenerateGoodsListBySid($shopId);
        return $res;
    }

    public function checkData($ids)
    {
        if (!$ids) {
            $this->error = '参数错误';
            return false;
        }
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $where['goods_id'] = ['in', $ids];
        $where['shop_id'] = request('shop_id');
        $res = $this->_getList($where)->toArray();
        if ($res) {
            foreach ($res as $v) {
                if ($v['status'] == 1) {
                    return false;
                }
            }
        }
        return true;
    }

    public function addOrUpdate()
    {
        $data['admin_id'] = plat_admin_id();
        $data['shop_id'] = intval(trim(request('shop_id')));
        $data['goods_name'] = trim(request('goods_name'));
        $data['goods_id'] = intval(trim(request('goods_id')));
        $data['pic_num'] = count(request('pics'));
        $data['goods_content'] = request('goods_content', '');
        $data['goods_price'] = floatval(trim(request('goods_price', 1)));
        $data['shop_price'] = floatval(trim(request('shop_price')));
        $data['goods_num'] = intval(trim(request('goods_num', 1)));
        $data['category_id'] = request('category_id');
        $data['bucket_category_id'] = request('bucket_category_id');
        $data['brand_id'] = request('brand_id');
        $data['status'] = request('status', 0);
        if (request('id')) {
            $data['id'] = trim(request('id'));
            $this->rules['goods_name'] .= ',' . $data['id'] . ',id,' . 'shop_id,' . request('shop_id'); //唯一字段验证,在更新时排除当前店铺中的当前商品id
        } else {
            $data['addtime'] = time();
        }
        if (!$this->_validate($data)) {
            return false;
        }
        //开启事务
//        $this->_start();
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存商品信息失败！';
//            $this->_rollBack(); //回滚
            return false;
        }
//        if (!isset($data['id'])) {
//            //新增商品同时更新shop表商品总数
//            $shop = new Shop();
//            $shop->_inc(['id' => $data['shop_id']], 'total_goods_num');
//        }
//        $id = isset($data['id']) ? $data['id'] : $this->id;
//        $picture = new Picture();
//        $res = $picture->upload($id);
//        if (!$res) {
//            $this->error = $picture->getError();
//            $this->_rollBack(); //回滚
//            return false;
//        }
//        //记录行为
//        action_log('update_goods', 'goods', $id);
//        //提交事务
//        $this->_commit();
        $this->_redisGenerateGoodsListBySid($data['shop_id']);
        return $res;
    }

    public function _redisGetGoodsListByShopId($shopId)
    {
        if (!$shopId) {
            $this->error = '非法操作';
            return false;
        }
        $category_id = request('category_id', 0);
        $page = request('page', 1);
        $table = $this->redisListTable;
        $key = 'shopid:' . $shopId . ':page:' . $page . ':category_id:' . $category_id;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            return unserialize($res[0]);
        }
        $this->_redisSetShopGoosListKeysBySid($shopId, $key);
        if ($category_id) {
            $category = new GoodsCategory();
            $arr = childTree($category->getCache(), $category_id, 'id', 'pid');
            $ids[] = $category_id;
            foreach ($arr as $v) {
                $ids[] = $v['id'];
            }
            $where['category_id'] = ['in', $ids];
        }
        $where['shop_id'] = $shopId;
        $where['status'] = ['>', 0];
        $order['sort'] = 'asc';
        $order['id'] = 'asc';
        $rows = $this->_getPageList($where, 'id,goods_id,goods_name,goods_num,sale_num,goods_price', $order);
        $this->redis->hmset($table, [$key => serialize($rows)]);
        return $rows;
    }

    public function _redisDelGoodsListByKey($key)
    {
        if (!$key) {
            $this->error = '非法操作';
            return false;
        }
        $table = $this->redisListTable;
        $this->redis->hdel($table, $key);
    }

    public function _redisSetShopGoosListKeysBySid($sid, $value)
    {
        if (!$value && !$sid) {
            $this->error = '非法操作';
            return false;
        }
        $table = $this->redisKeyTable;
        $key = $sid;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                $keyArr = unserialize($res[0]);
                if (in_array($value, $keyArr)) {
                    return false;
                }
                $keyArr[] = $value;
                return $this->redis->hmset($table, [$key => serialize($keyArr)]);
            }
        }
        $this->redis->hmset($table, [$key => serialize([$value])]);
    }

    public function _redisGetShopGoosListKeysBySid($sid)
    {
        if (!$sid) {
            $this->error = '非法操作';
            return false;
        }
        $table = $this->redisKeyTable;
        $key = $sid;
        $res = $this->redis->hmget($table, $key);
        if ($res) {
            return unserialize($res[0]);
        }
        return false;
    }

    public function _redisGenerateGoodsListBySid($sid)
    {
        if (!$sid) {
            $this->error = '非法操作';
            return false;
        }
        $keys = $this->_redisGetShopGoosListKeysBySid($sid);
        if ($keys && is_array($keys)) {
            foreach ($keys as $v) {
                $this->_redisDelGoodsListByKey($v);
            }
        }
    }

    public function _redisGenerateGoodsListByAid($aid)
    {
        $shop = new Shop();
        $res = $shop->_getList(['admin_id' => $aid], 'id')->toArray();
        if ($res) {
            foreach ($res as $v) {
                $keys = $this->_redisGetShopGoosListKeysBySid($v['id']);
                if ($keys && is_array($keys)) {
                    foreach ($keys as $v) {
                        $this->_redisDelGoodsListByKey($v);
                    }
                }
            }
        }

    }
}
